<template>
  <div class="teacher-dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <el-card class="welcome-card" shadow="hover">
        <div class="welcome-content">
          <div class="welcome-text">
            <h1>教师管理中心</h1>
            <p class="welcome-subtitle">{{ userStore.userName }} · {{ userStore.userInfo?.department }}</p>
            <p class="current-time">{{ currentTime }}</p>
          </div>
          <div class="welcome-stats">
            <div class="stat-item">
              <div class="stat-value">{{ stats.totalStudents }}</div>
              <div class="stat-label">管理学生</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.todaySubmissions }}</div>
              <div class="stat-label">今日提交</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ stats.pendingTasks }}</div>
              <div class="stat-label">待处理</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="24">
        <el-col :lg="6" :md="12" :sm="24">
          <ResultCard
            type="info"
            :icon="UserFilled"
            title="学生总数"
            :main-value="stats.totalStudents"
            unit="人"
            description="当前管理学生数量"
            :comparison="{ trend: 'up', value: '+5', text: '较上月' }"
            clickable
            @click="$router.push('/teacher/students')"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <ResultCard
            type="success"
            :icon="DocumentCopy"
            title="总提交次数"
            :main-value="stats.totalSubmissions"
            unit="次"
            description="累计论文提交"
            :comparison="{ trend: 'up', value: '+12%', text: '较上周' }"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <ResultCard
            type="warning"
            :icon="WarningFilled"
            title="高风险论文"
            :main-value="stats.highRiskCount"
            unit="篇"
            description="相似度超过30%"
            :comparison="{ trend: 'down', value: '-3', text: '较昨日' }"
          />
        </el-col>
        <el-col :lg="6" :md="12" :sm="24">
          <ResultCard
            type="info"
            :icon="TrendCharts"
            title="平均相似度"
            :main-value="stats.avgSimilarity"
            unit="%"
            description="全体学生平均值"
            :comparison="{ trend: 'down', value: '-2.1%', text: '较上月' }"
          />
        </el-col>
      </el-row>
    </div>

    <el-row :gutter="24">
      <!-- 快速操作 -->
      <el-col :lg="8" :md="12" :sm="24">
        <el-card class="quick-actions-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#409EFF">
                <Operation />
              </el-icon>
              <span>快速操作</span>
            </div>
          </template>

          <div class="quick-actions">
            <div class="action-item" @click="$router.push('/teacher/students')">
              <div class="action-icon">
                <el-icon size="24" color="#67C23A">
                  <User />
                </el-icon>
              </div>
              <div class="action-content">
                <h4>学生管理</h4>
                <p>管理学生信息和账号</p>
              </div>
              <el-icon class="action-arrow">
                <ArrowRight />
              </el-icon>
            </div>

            <div class="action-item" @click="showBatchImport">
              <div class="action-icon">
                <el-icon size="24" color="#E6A23C">
                  <Upload />
                </el-icon>
              </div>
              <div class="action-content">
                <h4>批量导入</h4>
                <p>批量导入学生信息</p>
              </div>
              <el-icon class="action-arrow">
                <ArrowRight />
              </el-icon>
            </div>

            <div class="action-item" @click="$router.push('/teacher/statistics')">
              <div class="action-icon">
                <el-icon size="24" color="#409EFF">
                  <TrendCharts />
                </el-icon>
              </div>
              <div class="action-content">
                <h4>数据统计</h4>
                <p>查看统计分析报告</p>
              </div>
              <el-icon class="action-arrow">
                <ArrowRight />
              </el-icon>
            </div>

            <div class="action-item" @click="exportAllData">
              <div class="action-icon">
                <el-icon size="24" color="#F56C6C">
                  <Download />
                </el-icon>
              </div>
              <div class="action-content">
                <h4>导出数据</h4>
                <p>导出学生和提交数据</p>
              </div>
              <el-icon class="action-arrow">
                <ArrowRight />
              </el-icon>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 提交趋势图表 -->
      <el-col :lg="16" :md="12" :sm="24">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#67C23A">
                <TrendCharts />
              </el-icon>
              <span>提交趋势</span>
              <div class="chart-controls">
                <el-radio-group v-model="chartPeriod" size="small">
                  <el-radio-button label="7d">近7天</el-radio-button>
                  <el-radio-button label="30d">近30天</el-radio-button>
                  <el-radio-button label="90d">近3个月</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>

          <div ref="chartRef" class="chart-container">
            <div class="chart-placeholder">
              <el-icon size="64" color="#C0C4CC">
                <TrendCharts />
              </el-icon>
              <p>图表占位 - 提交趋势分析</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最近活动和系统通知 -->
    <el-row :gutter="24">
      <!-- 最近活动 -->
      <el-col :lg="12" :md="24">
        <el-card class="activity-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#909399">
                <Clock />
              </el-icon>
              <span>最近活动</span>
              <el-button type="text" @click="refreshActivity">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </template>

          <div class="activity-list">
            <div
              v-for="activity in recentActivities"
              :key="activity.id"
              class="activity-item"
            >
              <div class="activity-avatar">
                <el-avatar :size="32">
                  {{ activity.studentName.charAt(0) }}
                </el-avatar>
              </div>
              <div class="activity-content">
                <p class="activity-text">
                  <strong>{{ activity.studentName }}</strong>
                  {{ activity.action }}
                  <span class="activity-target">{{ activity.target }}</span>
                </p>
                <p class="activity-time">{{ formatDateTime(activity.time) }}</p>
              </div>
              <div class="activity-status">
                <el-tag :type="getActivityTagType(activity.result)" size="small">
                  {{ activity.result }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 系统通知 -->
      <el-col :lg="12" :md="24">
        <el-card class="notification-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <el-icon size="20" color="#F56C6C">
                <Bell />
              </el-icon>
              <span>系统通知</span>
            </div>
          </template>

          <div class="notification-list">
            <div
              v-for="notification in notifications"
              :key="notification.id"
              class="notification-item"
              :class="{ 'is-unread': !notification.read }"
            >
              <div class="notification-icon">
                <el-icon :color="getNotificationColor(notification.type)">
                  <component :is="getNotificationIcon(notification.type)" />
                </el-icon>
              </div>
              <div class="notification-content">
                <h4>{{ notification.title }}</h4>
                <p>{{ notification.content }}</p>
                <span class="notification-time">{{ formatDateTime(notification.time) }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 班级统计 -->
    <el-card class="class-stats-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon size="20" color="#E6A23C">
            <School />
          </el-icon>
          <span>班级统计</span>
        </div>
      </template>

      <div class="class-stats-grid">
        <div
          v-for="classItem in classStats"
          :key="classItem.className"
          class="class-item"
          @click="viewClassDetail(classItem)"
        >
          <div class="class-header">
            <h4>{{ classItem.className }}</h4>
            <el-tag type="info" size="small">{{ classItem.totalStudents }}人</el-tag>
          </div>
          <div class="class-metrics">
            <div class="metric">
              <span class="metric-label">提交率</span>
              <el-progress
                :percentage="classItem.submissionRate"
                :stroke-width="8"
                :show-text="false"
              />
              <span class="metric-value">{{ classItem.submissionRate }}%</span>
            </div>
            <div class="metric">
              <span class="metric-label">平均相似度</span>
              <span class="metric-value">{{ classItem.avgSimilarity }}%</span>
            </div>
          </div>
        </div>
        
        <!-- 无数据提示 -->
        <div v-if="classStats.length === 0" class="empty-class-stats">
          <el-empty description="暂无班级统计数据" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
  UserFilled,
  DocumentCopy,
  WarningFilled,
  TrendCharts,
  Operation,
  User,
  Upload,
  Download,
  ArrowRight,
  Clock,
  Refresh,
  Bell,
  School,
  InfoFilled,
  SuccessFilled,
  CircleCloseFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import { formatDateTime } from '@/utils'
import ResultCard from '@/components/ResultCard.vue'
import { getOverviewStatistics, getTrendStatistics } from '@/api/teacher'

const router = useRouter()
const userStore = useUserStore()
const appStore = useAppStore()

// 当前时间
const currentTime = ref('')

// 统计数据
const stats = ref({
  totalStudents: 0,
  todaySubmissions: 0,
  pendingTasks: 0,
  totalSubmissions: 0,
  highRiskCount: 0,
  avgSimilarity: 0
})

// 图表周期
const chartPeriod = ref('7d')

// 监听图表周期变化
watch(chartPeriod, (newPeriod) => {
  updateChart()
})

// 最近活动
const recentActivities = ref([])

// 系统通知
const notifications = ref([])

// 班级统计
const classStats = ref([])

// 图表引用
const chartRef = ref()

// 定时器
let timer = null

// 更新时间
const updateTime = () => {
  currentTime.value = formatDateTime(new Date(), 'YYYY年MM月DD日 HH:mm:ss')
}

// 显示批量导入
const showBatchImport = () => {
  ElMessage.info('即将跳转到批量导入功能')
  router.push('/teacher/students')
}

// 导出所有数据
const exportAllData = () => {
  ElMessage.success('正在准备导出数据...')
}

// 刷新活动
const refreshActivity = () => {
  ElMessage.success('已刷新最近活动')
}

// 获取活动标签类型
const getActivityTagType = (result) => {
  const typeMap = {
    '已完成': 'success',
    '处理中': 'warning',
    '高风险': 'danger',
    '失败': 'danger'
  }
  return typeMap[result] || 'info'
}

// 获取通知图标颜色
const getNotificationColor = (type) => {
  const colorMap = {
    info: '#409EFF',
    warning: '#E6A23C',
    success: '#67C23A',
    error: '#F56C6C'
  }
  return colorMap[type] || '#909399'
}

// 获取通知图标
const getNotificationIcon = (type) => {
  const iconMap = {
    info: InfoFilled,
    warning: WarningFilled,
    success: SuccessFilled,
    error: CircleCloseFilled
  }
  return iconMap[type] || InfoFilled
}

// 查看班级详情
const viewClassDetail = (classItem) => {
  ElMessage.info(`查看 ${classItem.className} 详情`)
  router.push({
    path: '/teacher/students',
    query: { className: classItem.className }
  })
}

// 初始化图表
const initChart = async () => {
  if (!chartRef.value) return
  
  // 先加载图表数据
  await updateChart()
}

// 更新图表
const updateChart = async () => {
  if (!chartRef.value) return
  
  try {
    // 根据周期计算天数
    let days = 7
    if (chartPeriod.value === '30d') {
      days = 30
    } else if (chartPeriod.value === '90d') {
      days = 90
    }
    
    // 获取趋势数据
    const result = await getTrendStatistics({
      period: 'day',
      days: days
    })
    
    const trendData = result.data || result
    
    // 处理数据
    let dates = []
    let submissionData = []
    
    if (trendData.submissionTrends && Array.isArray(trendData.submissionTrends)) {
      // 按日期排序
      const sortedData = trendData.submissionTrends.sort((a, b) => {
        return new Date(a.date) - new Date(b.date)
      })
      
      dates = sortedData.map(item => item.date || '')
      submissionData = sortedData.map(item => item.submissions || 0)
    }
    
    // 初始化图表
    // 先清除可能存在的旧实例
    if (chartRef.value) {
      const existingChart = echarts.getInstanceByDom(chartRef.value);
      if (existingChart) {
        existingChart.dispose();
      }
      
      const chart = echarts.init(chartRef.value)
      
      const option = {
        title: {
          text: '提交趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: dates
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: submissionData,
            type: 'line',
            smooth: true,
            areaStyle: {}
          }
        ]
      }
      
      chart.setOption(option, true)
      
      // 监听窗口大小变化，重新调整图表大小
      const handleResize = () => {
        chart.resize()
      }
      window.addEventListener('resize', handleResize)
    }
  } catch (error) {
    console.error('加载图表数据失败:', error)
    ElMessage.error('图表数据加载失败')
  }
}

// 加载仪表盘数据
const loadDashboardData = async () => {
  try {
    console.log('开始加载仪表盘数据...')
    const result = await getOverviewStatistics()
    console.log('仪表盘API返回结果:', result)
    
    // 更新统计数据 - 使用正确的数据结构
    // 由于响应拦截器已经提取了data字段，直接使用result
    const basicStats = result.basicStats || {}
    const recentActivity = result.recentActivity || {}
    const riskAnalysis = result.riskAnalysis || {}
    
    stats.value = {
      totalStudents: basicStats.totalStudents || 0,
      todaySubmissions: recentActivity.todaySubmissions || 0,
      pendingTasks: 0, // 待处理任务需要单独接口
      totalSubmissions: basicStats.totalSubmissions || 0,
      highRiskCount: riskAnalysis.highRisk?.count || 0,
      avgSimilarity: basicStats.avgSimilarity || 0
    }
    
    console.log('更新后的stats:', stats.value)
    
    // 更新班级统计
    // 由于响应拦截器已经提取了data字段，直接使用result
    const classData = result.classDistribution || [];
    if (classData && Array.isArray(classData)) {
      console.log('班级分布数据:', classData)
      classStats.value = classData.map(item => {
        console.log('处理班级数据:', item)
        return {
          className: item.className || '未知班级',
          totalStudents: item.studentCount || 0,
          submissionRate: Math.round(item.completionRate || 0),
          avgSimilarity: Math.round((item.avgSimilarity || 0) * 10) / 10
        }
      })
      console.log('更新后的classStats:', classStats.value)
    } else {
      console.warn('未找到班级分布数据')
      console.log('API返回的完整数据:', result)
      // 即使没有数据也要初始化为空数组
      classStats.value = []
    }
    
    console.log('仪表盘数据加载完成')
  } catch (error) {
    console.error('加载仪表盘数据失败:', error)
    ElMessage.error('加载数据失败，请检查网络连接')
  }
}

onMounted(() => {
  appStore.setPageTitle('教师仪表盘')
  appStore.setBreadcrumbs([
    { title: '教师管理', path: '/teacher' },
    { title: '仪表盘', path: '/teacher/dashboard' }
  ])
  
  updateTime()
  timer = setInterval(updateTime, 1000)
  
  // 加载数据
  loadDashboardData()
  
  // 初始化图表
  nextTick(() => {
    initChart()
  })
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.teacher-dashboard {
  max-width: 1400px;
  margin: 0 auto;
}

/* 欢迎区域 */
.welcome-section {
  margin-bottom: 24px;
}

.welcome-card {
  border-radius: 12px;
  border: none;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.welcome-card :deep(.el-card__body) {
  padding: 2rem;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h1 {
  margin: 0 0 0.5rem 0;
  font-size: 2rem;
  font-weight: 600;
}

.welcome-subtitle {
  margin: 0 0 0.5rem 0;
  font-size: 1.1rem;
  opacity: 0.9;
}

.current-time {
  margin: 0;
  font-size: 1rem;
  opacity: 0.8;
}

.welcome-stats {
  display: flex;
  gap: 2rem;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: 700;
  margin-bottom: 0.25rem;
}

.stat-label {
  font-size: 0.9rem;
  opacity: 0.8;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 24px;
}

/* 卡片通用样式 */
.quick-actions-card,
.chart-card,
.activity-card,
.notification-card,
.class-stats-card {
  margin-bottom: 24px;
  border-radius: 12px;
  border: none;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.chart-controls {
  margin-left: auto;
}

/* 快速操作 */
.quick-actions {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-item:hover {
  border-color: #409EFF;
  background: #f0f9ff;
  transform: translateY(-2px);
}

.action-icon {
  flex-shrink: 0;
}

.action-content {
  flex: 1;
  min-width: 0;
}

.action-content h4 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.action-content p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-arrow {
  color: #c0c4cc;
  transition: color 0.3s ease;
}

.action-item:hover .action-arrow {
  color: #409EFF;
}

/* 图表容器 */
.chart-container {
  height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  text-align: center;
  color: #909399;
}

.chart-placeholder p {
  margin: 16px 0 0 0;
  font-size: 14px;
}

/* 活动列表 */
.activity-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.activity-content {
  flex: 1;
  min-width: 0;
}

.activity-text {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 14px;
}

.activity-target {
  color: #409EFF;
  font-weight: 500;
}

.activity-time {
  margin: 0;
  color: #909399;
  font-size: 12px;
}

.activity-status {
  flex-shrink: 0;
}

/* 通知列表 */
.notification-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.notification-item {
  display: flex;
  gap: 12px;
  padding: 12px;
  border-radius: 8px;
  transition: background 0.3s ease;
}

.notification-item.is-unread {
  background: #f0f9ff;
  border-left: 3px solid #409EFF;
}

.notification-icon {
  flex-shrink: 0;
  margin-top: 2px;
}

.notification-content {
  flex: 1;
  min-width: 0;
}

.notification-content h4 {
  margin: 0 0 4px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.notification-content p {
  margin: 0 0 4px 0;
  color: #606266;
  font-size: 13px;
  line-height: 1.4;
}

.notification-time {
  color: #909399;
  font-size: 12px;
}

/* 班级统计 */
.class-stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 16px;
  min-height: 200px;
}

.empty-class-stats {
  grid-column: 1 / -1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.class-item {
  padding: 16px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.class-item:hover {
  border-color: #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
}

.class-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.class-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.class-metrics {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.metric {
  display: flex;
  align-items: center;
  gap: 8px;
}

.metric-label {
  min-width: 80px;
  color: #606266;
  font-size: 14px;
}

.metric-value {
  min-width: 50px;
  text-align: right;
  color: #303133;
  font-weight: 600;
}

/* PC端优化设计 */
@media (max-width: 1200px) {
  .class-stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 992px) {
  .welcome-text h1 {
    font-size: 2rem;
  }
  
  .class-stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
    gap: 1rem;
  }
  
  .welcome-stats {
    justify-content: center;
    gap: 1rem;
  }
  
  .welcome-text h1 {
    font-size: 1.5rem;
  }
  
  .class-stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>

<script>
export default {
  name: 'TeacherDashboard'
}
</script>
